//
//  ImageViewModel.swift
//  FileManager-NSCache-HttpDownload
//
//  Created by DaleGuo on 2023/9/19.
//

import Combine
import Foundation
import SwiftUI

// 一张图片的viewModel

class ImageViewModel: ObservableObject {
    @Published var isLoading = true
    @Published var image: UIImage? = nil

    let urlString: String

    var cancellables = Set<AnyCancellable>()

    // 切换文件的存储方式Cache或File
//    let manager = PhotoModelDataCacheManager.instance
    let manager = PhotoModelDataFileManager.instance

    let imageKey: String

    // url为json中图片url,key用作manager中的key 这里用的是id
    init(url: String, key: String) {
        urlString = url
        imageKey = key
//        downloadImage()
        getImage()
    }

    func getImage() {
        if let savedImage = manager.get(key: imageKey) {
            print("getData from cache or file")
            image = savedImage
        } else {
            // 缓存中没有则下载图片
            downloadImage()
        }
    }

    func downloadImage() {
        print("Downloading from net in ImageViewModel")
        isLoading = true
        guard let url = URL(string: urlString) else {
            isLoading = false
            return
        }
        URLSession.shared.dataTaskPublisher(for: url)
//            .map({ (data: Data, response: URLResponse)->UIImage? in
//                return UIImage(data: data)
//            })
            .map { UIImage(data: $0.data) }
            .receive(on: DispatchQueue.main)
            .sink { [weak self] _ in
                // 下划线 忽略此参数
                self?.isLoading = false
            } receiveValue: { [weak self] returnedImage in
                // 因为多次用了self 所以可以确保
                guard
                    let self = self,
                    let image = returnedImage
                else {
                    return
                }
                self.image = image
                self.manager.add(key: self.imageKey, value: image)
            }
            .store(in: &cancellables)
    }
}
